#!/usr/bin/env python
# -*- coding: utf-8 -*-
from celery import Celery, platforms


class FlaskCelery(Celery):

    def __init__(self, app=None):
        super(FlaskCelery, self).__init__()
        if app is not None:
            self.init_app(app)

    def init_app(self, app):
        if not hasattr(app, 'extensions'):
            app.extensions = dict()
        if 'celery' in app.extensions:
            raise ValueError('Already registered extension CELERY.')
        super(FlaskCelery, self).__init__(app.import_name, broker=app.config['CELERY_BROKER_URL'])

        self.conf.update(app.config)
        TaskBase = self.Task

        class ContextTask(TaskBase):
            abstract = True

            def __call__(self, *args, **kwargs):
                with app.app_context():
                    return TaskBase.__call__(self, *args, **kwargs)
        self.Task = ContextTask

        app.extensions['celery'] = self


app_celery = FlaskCelery()

# 设置root用户启动
platforms.C_FORCE_ROOT = True
